<template>
  <TablePage>
    <template #top>
      <div class="flex flex-row items-center mb-4">
        <div class="font-semibold text-2xl text-color-header flex-1"> 网关类型 </div>
        <div>
          <!-- <PermissionBtn
            class="mr-2"
            :btn-props="{ type: 'primary', danger: true }"
            :oper-type="OperPermissionType.MANAGE"
            @click="del"
          >
            删除网关类型
            <template #icon>
              <Icon type="icon-shanchu" />
            </template>
          </PermissionBtn> -->
          <PermissionBtn
            v-if="!isEnterprise"
            :btn-props="{ type: isEnterprise ? 'default' : 'primary' }"
            :oper-type="OperPermissionType.MANAGE"
            @click="showCreateModal"
          >
            新增网关类型
            <template #icon>
              <Icon type="icon-tianjia" />
            </template>
          </PermissionBtn>
          <PermissionBtn
            v-if="isEnterprise"
            :btn-props="{ type: 'primary', loading: standardDataLoading }"
            :oper-type="OperPermissionType.MANAGE"
            @click="showTemplate"
          >
            使用标准模板
          </PermissionBtn>
        </div>
      </div>
    </template>
    <SlTable :columns="columns" row-key="id" :data-source="tableData" :pagination="undefined" :loading="tableLoading">
      <template #bodyCell="{ record, column }">
        <a-space v-if="column.dataIndex === 'oper'">
          <ViewGTPointAttrs
            v-if="isEnterprise"
            :gateway-type-id="record.gatewayTypeId"
            :btn-style="{ padding: 0, border: 0, height: 'auto' }"
          />
          <PermissionBtn
            v-else
            :btn-props="{ type: 'link' }"
            :oper-type="OperPermissionType.MANAGE"
            @click="handleSetAttr(record)"
          >
            设置属性
          </PermissionBtn>
          <PermissionBtn
            v-if="!isEnterprise"
            :btn-props="{ type: 'link' }"
            :oper-type="OperPermissionType.MANAGE"
            @click="showUpdateModal(record)"
          >
            编辑
          </PermissionBtn>
          <PermissionBtn
            v-if="record.defaultGatewayTypeId"
            :btn-props="{ type: 'link', danger: true }"
            :oper-type="OperPermissionType.MANAGE"
            @click="handleDel(record)"
          >
            删除
          </PermissionBtn>
        </a-space>
        <div v-else-if="column.dataIndex === 'isActive'">
          <a-switch
            :checked="record.isActive"
            checked-children="开"
            un-checked-children="关"
            :disabled="!isManagePermission"
            @change="activeChange(record)"
          />
        </div>
        <!-- <div v-else-if="column.dataIndex === 'gatewayTypeName'">
          <span class="mr-2">{{ record.gatewayTypeName }}</span>
          <a-tag :color="record.defaultGatewayTypeId ? 'processing' : 'success'">
            {{ record.defaultGatewayTypeId ? "标准化" : "自定义" }}
          </a-tag>
        </div> -->
      </template>
    </SlTable>
    <CreateGTModal v-model:visible="createVisible" :is-enterprise="isEnterprise" @done="gtDone" />
    <CURDDialog
      :id-key="mainKey"
      update-title="编辑网关类型信息"
      :model="gtModel"
      :model-form-setting="gtFormSetting"
      delete-message="您确定删除该网关类型吗？"
      :curd="curd"
      :show-options="showOptions"
      :reload-table="reloadTable"
      :table-data="tableData"
    />
    <SetAttr :options="setPointsOptions" :is-enterprise="isEnterprise" />
    <a-modal
      v-if="isEnterprise"
      v-model:visible="templateVisible"
      title="使用标准模板"
      :width="800"
      :ok-button-props="{ disabled: okDisabled }"
      @ok="handleCopy"
    >
      <CheckTreePanel
        v-model:value="selectedDefaultIds"
        search-placeholder="搜索网关类型"
        :tree-data="templateData"
        :disabled-value="disabledIds"
      ></CheckTreePanel>
    </a-modal>
  </TablePage>
</template>
<script lang="ts" setup>
import { onMounted, ref } from "vue";
import { OperPermissionType } from "/@/api/aiot/role/models";
import { useCURD } from "/@/hooks/useCURD";
import { Api, copyGatewayType, getManufacturerCode } from "/@/api/aiot/gateway";
import { GatewayTypeItem } from "/@/api/aiot/gateway/models";
import { useGatewayModel } from "./useGatewayModel";
import { CURDAction, ShowCURDModalOptions } from "/@/components/CURDDialog/models";
import { message, TableColumnProps } from "ant-design-vue";
import SetAttr from "./SetAttr.vue";
import type { DataNode } from "ant-design-vue/es/tree";
import { loopItem } from "/@/utils/treeData";
import { cloneDeep } from "lodash-es";
import { usePermission } from "/@/hooks/usePermission";

const props = defineProps<{
  isEnterprise: boolean;
}>();

const mainKey = props.isEnterprise ? "gatewayTypeId" : "defaultGatewayTypeId";

/**
 * table
 */
const { tableData, tableLoading, reloadTable, curd } = useCURD<Partial<GatewayTypeItem>>(
  props.isEnterprise
    ? {
        getPageUrl: Api.gatewayTypePage,
        updateUrl: Api.updateGatewayType,
        deleteUrl: Api.deleteByIds,
        loadOnMounted: false,
      }
    : {
        getPageUrl: Api.defaultGatewayTypePage,
        updateUrl: Api.updateDefaultGatewayType,
        deleteUrl: Api.deleteDefaultByIds,
        loadOnMounted: false,
      }
);
const { judgePermissionByOperType } = usePermission();
const isManagePermission = judgePermissionByOperType();

const columns = ref<TableColumnProps[]>([
  {
    title: "网关类型名称",
    dataIndex: "gatewayTypeName",
  },
  {
    title: "网关类型代码",
    dataIndex: "gatewayTypeCode",
  },
  {
    title: "厂商标识",
    dataIndex: "manufacturerCode",
    customRender({ text }) {
      const item = manufacturerData.find((el) => el.value === text);
      return item ? item.text : "--";
    },
  },
  {
    title: "是否启用",
    dataIndex: "isActive",
  },
  {
    title: "操作",
    dataIndex: "oper",
  },
]);
const { gtModel, gtFormSetting } = useGatewayModel(props.isEnterprise);
let manufacturerData: { value: string; text: string }[] = [];
onMounted(async () => {
  tableLoading.value = true;
  const data = await getManufacturerCode(true);
  if (data) {
    manufacturerData = data;
  }
  tableLoading.value = false;
  reloadTable();
});
/**
 * table oper
 */
const createVisible = ref(false);
function showCreateModal() {
  createVisible.value = true;
}
function handleDel(record: GatewayTypeItem) {
  showOptions.value = { ids: [record[mainKey] as string], action: CURDAction.DELETE };
}
function gtDone() {
  reloadTable();
}
async function activeChange(record: GatewayTypeItem) {
  if (!curd.update) return;
  const re = await curd.update({
    [mainKey]: record[mainKey],
    isActive: !record.isActive,
  });
  if (re) {
    message.success("操作成功");
    reloadTable();
  }
}
const setPointsOptions = ref<{ gatewayTypeId: string }>();
function handleSetAttr(record: GatewayTypeItem) {
  setPointsOptions.value = {
    gatewayTypeId: record[mainKey] as string,
  };
}
/**
 * update gateway dialog
 */
const showOptions = ref<ShowCURDModalOptions>();
function showUpdateModal(record: GatewayTypeItem) {
  showOptions.value = { record, action: CURDAction.UPDATE };
}

/**
 * 复制平台标准类型
 */
const templateVisible = ref(false);
const selectedDefaultIds = ref<string[]>([]);
const disabledIds = ref<string[]>([]);
const templateData = ref<DataNode[]>([]);
const okDisabled = ref(false);
const {
  tableData: standardData,
  tableLoading: standardDataLoading,
  reloadTable: reloadStandardData,
} = useCURD<GatewayTypeItem>({
  getPageUrl: Api.defaultGatewayTypePage,
  pageSize: 999,
  loadOnMounted: false,
  loadFilter(data) {
    data = data.filter((el) => {
      return el.isActive;
    });
    // data.push({
    //   key: "test",
    //   defaultGatewayTypeId: "test",
    //   gatewayTypeName: "test",
    //   children: [
    //     { defaultGatewayTypeId: "1", gatewayTypeName: "1111" },
    //     { defaultGatewayTypeId: "2", gatewayTypeName: "2222" },
    //     {
    //       defaultGatewayTypeId: "3",
    //       gatewayTypeName: "3333",
    //       children: [
    //         { defaultGatewayTypeId: "3-1", gatewayTypeName: "3333-1111" },
    //         { defaultGatewayTypeId: "3-2", gatewayTypeName: "3333-2222" },
    //         { defaultGatewayTypeId: "3-3", gatewayTypeName: "3333-3333" },
    //       ],
    //     },
    //     { defaultGatewayTypeId: "4", gatewayTypeName: "4444" },
    //     { defaultGatewayTypeId: "5", gatewayTypeName: "5555" },
    //   ],
    // });
    return data;
  },
});
async function showTemplate() {
  if (standardData.value.length === 0) {
    await reloadStandardData();
  }
  const copyData = cloneDeep<GatewayTypeItem[]>(standardData.value);
  //已选的标准类型id
  // const _selectedDefaultIds: string[] = ["3-1", "3-2"];
  const _selectedDefaultIds: string[] = [];
  let sum = 0;
  loopItem<GatewayTypeItem>(copyData, (item) => {
    item.key = item.defaultGatewayTypeId as string;
    item.title = item.gatewayTypeName;
    sum++;
  });
  loopItem<Partial<GatewayTypeItem>>(tableData.value, (el) => {
    if (el.defaultGatewayTypeId) {
      _selectedDefaultIds.push(el.defaultGatewayTypeId);
    }
  });
  selectedDefaultIds.value = _selectedDefaultIds;
  disabledIds.value = [..._selectedDefaultIds];
  okDisabled.value = _selectedDefaultIds.length === sum;
  templateData.value = copyData;
  templateVisible.value = true;
}
async function handleCopy() {
  const copyData: Partial<GatewayTypeItem>[] = [];
  selectedDefaultIds.value.forEach((id) => {
    if (disabledIds.value.includes(id)) {
      //已经添加过 不重复添加
      return;
    }
    const item = standardData.value.find((el) => el.defaultGatewayTypeId === id);
    if (item) {
      copyData.push(item);
    }
  });
  if (copyData.length === 0) {
    return message.info("请至少勾选一个新的网关类型");
  }
  const re = await copyGatewayType(copyData);
  if (re) {
    message.success("操作成功");
    templateVisible.value = false;
    selectedDefaultIds.value = [];
    reloadTable();
  }
}
</script>
